var fotoString = require('../lib/fotostring');
var fotoNumber = require('../lib/fotonumber');
var message = require('../lib/message');
var database = require('../lib/database');
var codeOperation = require('../lib/code');
var fs = require('fs');
var util = require('util');
var path = require('path');

module.exports = {
	getExtension : function(fileName) {
		var result = fotoString.EMPTY_STRING;
		if(fileName.indexOf(fotoString.DOT) != fotoNumber.NEGATIVE_ONE){
			var splitExtension = fileName.split(fotoString.DOT);
			result = splitExtension[splitExtension.length - fotoNumber.POSITIVE_ONE];
		}
		return result;
	},
	
	uploadImage : function(image, fileName, uploadOption){
		var tempPath = image.path;
		var path = fotoString.EMPTY_STRING;
		
		switch (uploadOption) {
			case fotoNumber.AVATAR:
					path = fotoString.AVATAR_PATH;
				break;
				
			case fotoNumber.PHOTO:
					path = fotoString.PHOTO_PATH;
				break;	
				
			case fotoNumber.THUMBNAIL:
					path = fotoString.THUMBNAIL_PATH;
				break;
				
		}
		
		var savePath = path + fileName + fotoString.DOT + this.getExtension(image.name);
		var inputStrean = fs.createReadStream(tempPath);
		var outputStream = fs.createWriteStream(savePath);
		
		try {
			util.pump(inputStrean, outputStream, function() {
			    fs.unlinkSync(tempPath);
			});
			database.closeDatabase();
		} catch (uploadError) {
			code = codeOperation.OPERATION_ERROR;
			result = message.MESSAGE_UPLOAD_ERROR;
			response.json({"code" : code, "result": result} );
			database.closeDatabase();
			return;
		}
		return savePath;
	}
	,
	copyImageToTemp : function(fileName, sourceImageUrl){
		var savePath = fotoString.TEMP_PATH + fileName + fotoString.DOT + this.getExtension(sourceImageUrl);
		var inputStrean = fs.createReadStream(sourceImageUrl);
		var outputStream = fs.createWriteStream(savePath);
		
		try {
			inputStrean.pipe(outputStream);
			database.closeDatabase();
		} catch (uploadError) {
			code = codeOperation.OPERATION_ERROR;
			result = message.MESSAGE_UPLOAD_ERROR;
			response.json({"code" : code, "result": result} );
			database.closeDatabase();
			return;
		}
		var linkAvatar = fotoString.HOST + savePath.replace(fotoString.DOT + fotoString.BIAS + fotoString.PUBLIC + fotoString.BIAS, fotoString.BIAS); 
		return linkAvatar;
	},
	 
	deleteImage : function(filePath){
		try {
			fs.unlink(filePath, function (error) {
				if(error){
					database.closeDatabase();
				}
			});
		} catch (deleteFileError) {
			database.closeDatabase();
			return;
		}
	}
}

